import {
    extractBoundaryMapping,
    searchSentenceByBoundaryMapping,
} from 'text-search-engine'
import redis from "@/utils/redis.mjs";
import { returnResponse } from "@/utils/index.mjs";
function mergeSpacesWithRanges(source, rawHitRanges) {
    if (rawHitRanges.length === 1) return rawHitRanges
    const hitRanges = [rawHitRanges[0]]
    let [lastStart, lastEnd] = rawHitRanges[0]
    for (let i = 1; i < rawHitRanges.length; i++) {
        const [start, end] = rawHitRanges[i]
        const gap = source.slice(lastEnd + 1, start)

        // between two ranges, there is a blank space
        if (!gap.trim().length) {
            hitRanges[hitRanges.length - 1] = [lastStart, end]
        } else {
            lastStart = start
            hitRanges.push([start, end])
        }
        lastEnd = end
    }
    return hitRanges
}
let carConfig = []
try {
    carConfig = await redis.lrange('cars:config6', 0, -1)
    carConfig = carConfig.map(item => JSON.parse(item))
    console.log(carConfig)
} catch (e) {
    console.log(e)
}
// 从/crawler/carConfig.json中读取数据
const originalList = carConfig.map(item => item.name.startsWith(item.brand_name) ? item.name : `${item.brand_name} ${item.name}`)
const sourceMappingArray = originalList.map((item) => ({
    ...extractBoundaryMapping(item.toLocaleLowerCase()),
    passValue: item,
}))
function highlightMatches(text, hitRanges) {
    // 创建一个可操作的文本副本
    let highlightedText = '';

    // 当前文本的位置指针
    let currentPos = 0;

    // 遍历所有的匹配范围
    hitRanges.forEach(([start, end]) => {
        // 如果当前指针与开始位置之间有文本，则添加这部分文本（非匹配部分）
        if (currentPos < start) {
            highlightedText += text.substring(currentPos, start);
        }

        // 添加高亮的匹配文本
        highlightedText += `<span style="color:#007aff;">${text.substring(start, end + 1)}</span>`;

        // 更新当前指针位置为结束位置
        currentPos = end + 1;
    });

    // 如果还有剩余的文本没有处理（即不在任何匹配范围内），则追加它
    if (currentPos < text.length) {
        highlightedText += text.substring(currentPos);
    }

    return {highlightedText, text};
}
export async function POST(request) {
    // 从body中获取phone和pwd
    const formData = await request.json()
    const inputValue = formData.keyword
    const filteredData = sourceMappingArray
        .reduce((acc, item) => {
        const hitRanges = searchSentenceByBoundaryMapping(item, inputValue.trim().toLocaleLowerCase())
        hitRanges &&
        acc.push({
            passValue: item.passValue,
            hitRanges: mergeSpacesWithRanges(item.passValue, hitRanges),
        })
        return acc
    }, [])
        .sort((a, b) => {
            if (a.hitRanges && b.hitRanges) {
                return a.hitRanges.length - b.hitRanges.length
            }
            return 0
        })
    const list = filteredData.map(item => highlightMatches(item.passValue, item.hitRanges)).map(item => ({content: item.highlightedText, originText: item.text})).splice(0, 10)
    return returnResponse({list})
}
